﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyDDD.AdminModule.Application.CommandsSysAdminRole
{
    /// <summary>
    /// 设置管理员权限声明
    /// </summary>
    public record SysAdminRoleSetRoleClaimCommand : ICommand
    {
        public Guid Id { get; set; }

        public ICollection<SysAdminRoleSetRoleClaimCommandItem> RoleClaimList { get; set; } = new Collection<SysAdminRoleSetRoleClaimCommandItem>();
    }

    [AutoMapperTo(typeof(EasyDDD.Domain.User.ApplicationRoleClaim))]
    public record SysAdminRoleSetRoleClaimCommandItem
    {
        public string ClaimType { get; set; } = default!;

        public string ClaimValue { get; set; } = default!;
    }

    public class SysAdminRoleSetRoleClaimCommandValidator : AbstractValidator<SysAdminRoleSetRoleClaimCommand>
    {
        public SysAdminRoleSetRoleClaimCommandValidator()
        {
            RuleFor(x => x.RoleClaimList)
             .ForEach(roleClaim =>
             {
                 roleClaim.Must(item => string.IsNullOrEmpty(item.ClaimType)).WithMessage("ClaimType不能为空");
                 roleClaim.Must(item => string.IsNullOrEmpty(item.ClaimValue)).WithMessage("ClaimValue不能为空");
             });
        }
    }

    public class SysAdminRoleSetRoleClaimCommandHandler(
       IMapper mapper,
       Repository.SysAdminRoleRepository repository,
       ILogger<SysAdminRoleSetRoleClaimCommandHandler> logger)
       : ICommandHandler<SysAdminRoleSetRoleClaimCommand>
    {
        public async Task Handle(SysAdminRoleSetRoleClaimCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysAdminRoleSetRoleClaimCommandHandler");
            var list = mapper.Map<List<EasyDDD.Domain.User.ApplicationRoleClaim>>(request.RoleClaimList);
            var entity = await repository.GetAsync(request.Id);
            entity.SetRoleClaimList(list);
        }
    }

}
